<template>
	<view class="edit-page">
		<view class="contentBox">
			<view class="form-title">基本信息</view>
			<view class="form-list">
				<view class="form-item">
					<view class="title required">区域</view>
					<view class="value-box" @click="selectZone">
						<view class="value-info">{{dataForm.zone?dataForm.zone:'请选择'}}</view>
						<u-icon name="arrow-right" color="#000000"></u-icon>
					</view>
				</view>
				<view class="form-item">
					<view class="title required">大楼</view>
					<view class="value-box" @click="selectBuilding">
						<view class="value-info">{{dataForm.address?dataForm.address:'请选择'}}</view>
						<u-icon name="arrow-right" color="#000000"></u-icon>
					</view>
				</view>
				<view class="form-item">
					<view class="title required">房号</view>
					<input v-model="dataForm.name" placeholder="请输入房号" class="input" />
					<view class="unit">RBC</view>
				</view>
			</view>
			<view class="form-title">
				<view class="title">选填信息</view>
				<view class="form-switch">
					<u-switch v-model="isSelectFill" :activeValue="true" :inactiveValue="false"
						active-color="#fe4f04"></u-switch>
				</view>
			</view>
			<view class="form-list" v-if="isSelectFill">
				<view class="form-item">
					<view class="title">价格</view>
					<input v-model="dataForm.price" placeholder="请输入房租" class="input" type="digit" />
					<view class="unit">元/月</view>
				</view>
				<view class="form-item">
					<view class="title">类型</view>
					<view class="value-box" @click="showPopup = true">
						<view class="value-info">{{dataForm.type?formatFormType(dataForm.type):'请选择'}}</view>
						<u-icon name="arrow-right" color="#000000"></u-icon>
					</view>
				</view>
				<view class="form-item" v-if="dataForm.type==1">
					<view class="title">户型</view>
					<view class="value-box" @click="$Tips('/pages-landlord/settings/house?pageType=select')">
						<view class="value-info">{{dataForm.house_type?dataForm.house_type:'请选择'}}</view>
						<u-icon name="arrow-right" color="#000000"></u-icon>
					</view>
				</view>
				<view class="form-item">
					<view class="title">楼层</view>
					<input v-model="dataForm.floor_no" placeholder="请输入楼层" class="input" />
					<view class="unit">楼</view>
				</view>
				<view class="form-item">
					<view class="title">面积</view>
					<input v-model="dataForm.area" placeholder="请输入面积" class="input" type="digit" />
					<view class="unit">㎡</view>
				</view>
			</view>
			<view class="select-box" v-if="isSelectFill">
				<view class="select-title">
					<view class="title">水电表</view>
					<image src="/pages-landlord/static/room/select-add.png" class="icon-select"
						@click="selectMeterInfo"></image>
				</view>
				<view class="select-list">
					<view class="select-item" v-for="(item, index) in dataForm.board" :key="index"
						@click="updateMeterInfo(item)">
						<view class="item-left">{{item.name}}</view>
						<view class="item-right">
							<view class="item-text">{{item.price}} {{meterUnitFormat(item.type)}}</view>
							<u-icon name="arrow-right" color="#000000"></u-icon>
						</view>
					</view>
				</view>
			</view>
			<view class="select-box" v-if="isSelectFill">
				<view class="select-title">
					<view class="title">固定费用</view>
					<image src="/pages-landlord/static/room/select-add.png" class="icon-select"
						@click="selectFixedCosts"></image>
				</view>
				<view class="select-list">
					<view class="select-item" v-for="(item, index) in dataForm.fixed" :key="index"
						@click="updateFixedCosts(item)">
						<view class="item-left">{{item.type_name}}</view>
						<view class="item-right">
							<view class="item-text">{{item.price}} {{fixedUnitFormat(item.pay_type)}}</view>
							<u-icon name="arrow-right" color="#000000"></u-icon>
						</view>
					</view>
				</view>
			</view>
			<view class="select-box" v-if="isSelectFill">
				<view class="select-title">
					<view class="title">配套设备</view>
					<image src="/pages-landlord/static/room/select-add.png" class="icon-select"
						@click="selectSupportInfo"></image>
				</view>
				<view class="select-list">
					<view class="select-item" v-for="(item, index) in dataForm.pt" :key="index"
						@click="updateSupportInfo(item)">
						<view class="item-left">{{item.name}}</view>
						<view class="item-right">
							<view class="item-text">{{item.deposit}}元</view>
							<u-icon name="arrow-right" color="#000000"></u-icon>
						</view>
					</view>
				</view>
			</view>
			<view class="select-box" v-if="isSelectFill">
				<view class="select-title">
					<view class="title">其他信息</view>
					<input type="text" v-model="dataForm.remark" placeholder="备注" class="input">
				</view>
			</view>
			<view class="fillBox" style="height: 150rpx;"></view>
			<view class="safe-bottom page-bottom">
				<view class="action-btn-group">
					<view class="action-btn1" @click="cancelSave">取 消</view>
					<view class="action-btn2" @click="$u.throttle(confirmSave, 2000)">添 加</view>
				</view>
			</view>
		</view>
		<u-popup :show="showPopup" mode="bottom" :closeOnClickOverlay="false" round="40rpx">
			<view class="filter-modal">
				<view class="header">
					<text @click="handleCancel">取消</text>
					<text style="font-weight: bold">类型</text>
					<text class="confirm" @click="handleConfirm">确认</text>
				</view>
				<view class="fill-box"></view>
				<view class="section-box">
					<!--					<view class="title">类型</view>-->
					<view class="tags-box">
						<view :class="selectTypeInfo.value===item.value?'tag-item active':'tag-item'"
							v-for="(item, index) in propertyTypes" :key="index" @click="selectTypeInfo=item">
							{{item.text}}
						</view>
					</view>
				</view>
			</view>
		</u-popup>
		<u-picker :show="showHxPicker" :columns="houseTypeList" keyName="name" @cancel="showHxPicker = false"
			@confirm="confirmSelectHx"></u-picker>
	</view>
</template>

<script>
	import {
		roomAdd,
		hxList
	} from '@/api/landlord'
	// 定义事件名称常量（避免魔法字符串）
	const EVENT_TYPES = {
		ZONE_SELECT: 'selectZone',
		BUILDING_SELECT: 'selectBuilding',
		HOUSE_TYPE_SELECT: 'selectHouseType',
		METER_SELECT: 'selectRoomMeterInfo',
		METER_DELETE: 'deleteRoomMeterInfo',
		FIXED_COST_SELECT: 'selectRoomFixedCosts',
		FIXED_COST_DELETE: 'deleteRoomFixedCosts',
		SUPPORT_SELECT: 'selectRoomSupportInfo',
		SUPPORT_DELETE: 'deleteRoomSupportInfo'
	};

	export default {
		data() {
			return {
				showPopup: false, // 是否显示筛选弹窗
				isSelectFill: false, // 是否选填信息
				dataForm: {
					"address": "",
					"name": "",
					"build_id": "",
					"type": "",
					"house_type": "",
					"area": "",
					"floor_no": "",
					"price": "",
					"images": "",
					"remark": "",
					"board": [],
					"fixed": [],
					"pt": []
				},
				propertyTypes: [{
					text: '居住',
					value: 1
				}, {
					text: '商铺',
					value: 2
				}, {
					text: '厂房',
					value: 3
				}, {
					text: '办公',
					value: 4
				}, {
					text: '仓库',
					value: 5
				}, {
					text: '建材',
					value: 6
				}, {
					text: '物业',
					value: 7
				}, {
					text: '车位',
					value: 8
				}],
				houseTypeList: [], // 户型列表
				showHxPicker: false, // 是否显示户型选择器
				selectTypeInfo: '', // 选中的类型
			}
		},
		onLoad(options) {
			console.log(options);
			if (options && options.build_id) {
				this.dataForm.build_id = options.build_id;
				this.dataForm.address = options.address;
				this.dataForm.zone = options.zone;
			}
			//复制房源信息
			if (options && options.dataInfo) {
				let dataInfo = JSON.parse(options.dataInfo);
				this.dataForm = {
					address: dataInfo.address,
					name: dataInfo.name,
					build_id: dataInfo.build_id,
					zone: dataInfo.zone,
					type: dataInfo.type,
					house_type: dataInfo.house_type,
					area: dataInfo.area,
					floor_no: dataInfo.floor_no,
					price: dataInfo.price,
					images: dataInfo.images,
					remark: dataInfo.remark,
					board: dataInfo.board || [],
					fixed: dataInfo.fixed || [],
					pt: dataInfo.pt || []
				}

			}
		},
		onShow() {
			this.initEventListeners()
			this.getHxList();
		},
		methods: {
			// 获取户型列表
			getHxList() {
				hxList().then(res => {
					this.houseTypeList = [res.data.data]
				});
			},
			//选择户型
			confirmSelectHx(event) {
				console.log(event);
				this.showHxPicker = false;
				this.dataForm.house_type = event.value[0].name;
			},
			// 初始化事件监听
			initEventListeners() {
				// 区域选择
				uni.$on(EVENT_TYPES.ZONE_SELECT, this.handleZoneSelect);

				// 建筑选择
				uni.$on(EVENT_TYPES.BUILDING_SELECT, this.handleBuildingSelect);

				// 户型选择
				uni.$on(EVENT_TYPES.HOUSE_TYPE_SELECT, this.handleHouseTypeSelect);

				// 水电表管理
				uni.$on(EVENT_TYPES.METER_SELECT, (data) => this.handleItemUpdate(data, 'board', 'type', true));
				uni.$on(EVENT_TYPES.METER_DELETE, (data) => this.handleItemDelete(data, 'board', 'type'));

				// 固定费用管理
				uni.$on(EVENT_TYPES.FIXED_COST_SELECT, (data) => this.handleItemUpdate(data, 'fixed', 'type_name', true));
				uni.$on(EVENT_TYPES.FIXED_COST_DELETE, (data) => this.handleItemDelete(data, 'fixed', 'type_name'));

				// 配套设备管理
				uni.$on(EVENT_TYPES.SUPPORT_SELECT, (data) => this.handleItemUpdate(data, 'pt', 'name', true));
				uni.$on(EVENT_TYPES.SUPPORT_DELETE, (data) => this.handleItemDelete(data, 'pt', 'name'));

			},
			// 移除事件监听
			removeEventListeners() {
				uni.$off(EVENT_TYPES.ZONE_SELECT);
				uni.$off(EVENT_TYPES.BUILDING_SELECT);
				uni.$off(EVENT_TYPES.HOUSE_TYPE_SELECT);
				uni.$off(EVENT_TYPES.METER_SELECT);
				uni.$off(EVENT_TYPES.METER_DELETE);
				uni.$off(EVENT_TYPES.FIXED_COST_SELECT);
				uni.$off(EVENT_TYPES.FIXED_COST_DELETE);
				uni.$off(EVENT_TYPES.SUPPORT_SELECT);
				uni.$off(EVENT_TYPES.SUPPORT_DELETE);
			},
			// 处理区域选择
			handleZoneSelect(zone) {
				if (zone) {
					this.dataForm.zone_id = zone.id;
					this.dataForm.zone = zone.name;
				}
			},
			// 处理建筑选择
			handleBuildingSelect(building) {
				if (building) {
					this.dataForm.address = building.address;
					this.dataForm.build_id = building.id;
					this.removeEventListeners();
				}
			},
			// 处理户型选择
			handleHouseTypeSelect(houseType) {
				if (houseType) {
					this.dataForm.house_type = houseType.name;
					this.removeEventListeners();
				}
			},
			/**
			 * 通用更新/添加逻辑
			 * @param {Object} data 新数据
			 * @param {String} arrayKey dataForm 中的数组键名
			 * @param {String} matchKey 匹配字段名
			 * @param {Boolean} needSelectFill 是否需要设置 isSelectFill
			 */
			handleItemUpdate(data, arrayKey, matchKey, needSelectFill = false) {
				if (!data) return;

				if (needSelectFill) this.isSelectFill = true;

				// 使用 findIndex 查找是否已存在
				const existingIndex = this.dataForm[arrayKey].findIndex(
					item => item[matchKey] === data[matchKey]
				);

				// 存在则更新，不存在则添加
				if (existingIndex !== -1) {
					// UniApp 中直接修改数组元素通常是响应式的
					this.dataForm[arrayKey].splice(existingIndex, 1, data);
				} else {
					this.dataForm[arrayKey].push(data);
				}

				this.removeEventListeners();
			},

			/**
			 * 通用删除逻辑
			 * @param {Object} data 要删除的数据（只需包含匹配字段）
			 * @param {String} arrayKey dataForm 中的数组键名
			 * @param {String} matchKey 匹配字段名
			 */
			handleItemDelete(data, arrayKey, matchKey) {
				if (!data) return;

				const index = this.dataForm[arrayKey].findIndex(
					item => item[matchKey] === data[matchKey]
				);

				if (index !== -1) {
					this.dataForm[arrayKey].splice(index, 1);
				}
				this.removeEventListeners()
			},
			handleCancel() {
				this.showPopup = false;
			},
			handleConfirm() {
				this.showPopup = false;
				// 处理确认逻辑
				if (this.selectTypeInfo) {
					this.dataForm.type = this.selectTypeInfo.value;
				}
			},
			formatFormType(type) {
				const typeIndex = this.propertyTypes.findIndex(item => item.value === type);
				return typeIndex !== -1 ? this.propertyTypes[typeIndex].text : '请选择';
			},
			selectZone() {
				uni.navigateTo({
					url: '/pages-landlord/room-manage/select-zone'
				})
			},
			selectBuilding() {
				uni.navigateTo({
					url: '/pages-landlord/select-building/select-building?zone_id=' + this.dataForm.zone_id +
						'&zone=' + this.dataForm.zone
				})
			},
			selectMeterInfo() {
				uni.navigateTo({
					url: '/pages-landlord/room-manage/instrument-details'
				})
			},
			updateMeterInfo(item) {
				uni.navigateTo({
					url: '/pages-landlord/room-manage/instrument-details?dataInfo=' + JSON.stringify(item)
				})
			},
			meterUnitFormat(type) {
				switch (type) {
					case 1:
						return '元/吨';
					case 2:
						return '元/度';
					case 3:
						return '元/立方米';
					case 4:
						return '元/升';
					default:
						return '';
				}
			},
			selectFixedCosts() {
				uni.navigateTo({
					url: '/pages-landlord/room-manage/fixed-costs'
				})
			},
			updateFixedCosts(item) {
				uni.navigateTo({
					url: '/pages-landlord/room-manage/fixed-costs?dataInfo=' + JSON.stringify(item)
				})
			},
			fixedUnitFormat(type) {
				switch (type) {
					case 1:
						return '随房租付';
					case 2:
						return '元/年';
					case 3:
						return '元/半年';
					case 4:
						return '一次性付';
					case 5:
						return '元/月';
					case 6:
						return '元/季';
					default:
						return '';
				}
			},
			selectSupportInfo() {
				uni.navigateTo({
					url: '/pages-landlord/room-manage/support-detail'
				})
			},
			updateSupportInfo(item) {
				uni.navigateTo({
					url: '/pages-landlord/room-manage/support-detail?dataInfo=' + JSON.stringify(item)
				})
			},
			// 提交信息
			confirmSave() {
				if (!this.dataForm.build_id) {
					return this.$Toast('请选择大楼');
				}
				if (!this.dataForm.name) {
					return this.$Toast('请输入房号');
				}
				roomAdd(this.dataForm).then(res => {
					this.$Toast('添加房间成功')
					uni.reLaunch({
						url: "/pages-landlord/index?tabBarIndex=3",
					});
					// this.$Tips({
					// 	title: '添加房间成功'
					// }, {
					// 	url: '/pages-landlord/index',
					// 	tab: 4
					// });
				})
			},
			// 取消保存
			cancelSave() {
				uni.navigateBack({
					delta: 1
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.filter-modal {
		background: #fff;
		height: 30vh;
		border-radius: 40rpx 40rpx 0 0;
		overflow-y: scroll;

		.header {
			position: fixed;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 40rpx;
			box-sizing: border-box;
			height: 120rpx;
			border-radius: 40rpx 40rpx 0 0;
			border-bottom: 1px solid #eee;
			background: #ffffff;
			z-index: 100;

			.confirm {
				color: #FE4F04;
			}
		}

		.fill-box {
			height: 120rpx;
		}

		.section-box {
			padding: 0 20rpx;
			margin: 20rpx 0 40rpx;

			.title {
				font-size: 28rpx;
				color: #222222;
				font-weight: 600;
				margin-bottom: 20rpx;
			}

		}

		.tags-box {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;

			.tag-item {
				font-size: 28rpx;
				height: 68rpx;
				line-height: 68rpx;
				padding: 0rpx 50rpx;
				border-radius: 40rpx;
				background: #F5F6FA;
				border: 1rpx solid #F5F6FA;
			}

			.tag-item.active {
				color: #FF7D41;
				background: #FFF6ED;
				border: 1rpx solid #FE4F04;
			}
		}
	}

	/* 底部操作菜单 */
	.page-bottom {
		position: fixed;
		width: 100%;
		bottom: 0rpx;
		z-index: 200;
		display: flex;
		justify-content: space-around;
		align-items: center;
		background: #ffffff;
		border-radius: 16rpx;
		padding: 20rpx;
		box-sizing: border-box;

		button {
			margin: unset;
			padding: unset;
			background-color: #ffffff;
		}

		button::after {
			border: none;
		}

		.icon-box {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			font-size: 22rpx;
			color: #333333;
			margin-right: 48rpx;

			.label {
				font-size: 22rpx;
				color: #333333;
				margin-top: 6rpx;
			}
		}

		.action-btn-group {
			display: flex;
			align-items: center;
			justify-content: center;
			overflow: hidden;
			flex: 1;

			.action-btn1,
			.action-btn2 {
				width: 100%;
				height: 88rpx;
				font-weight: bold;
				font-size: 30rpx;
				line-height: 88rpx;
				text-align: center;
				border-radius: 44rpx;
				border: 2rpx solid #FE4F04;
			}

			.action-btn1 {
				color: #FE4F04;
				background: #fff;
				margin-right: 10rpx;
			}

			.action-btn2 {
				color: #fff;
				background: #FE4F04;
				margin-left: 10rpx;
			}
		}
	}

	.edit-page {
		width: 100%;
		min-height: 100vh;
		background-color: #F7F8FA;

		.contentBox {
			padding-bottom: 40rpx;
		}
	}

	.form-switch {
		margin-top: 40rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.form-title {
		font-weight: bold;
		font-size: 26rpx;
		color: #2A0C00;
		margin: 24rpx 72rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.form-list {
		padding: 34rpx 40rpx;
		border-radius: 16rpx;
		margin: 20rpx 32rpx;
		background: #FFFFFF;

		.form-item {
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.title {
				width: 180rpx;
				font-size: 28rpx;
				color: #666666;
			}

			.required::after {
				content: '*';
				color: #FE4F04;
				padding-left: 10rpx;
				font-size: 28rpx;
				font-weight: bold;
			}

			.unit {
				font-size: 28rpx;
				color: #222222;
				margin-left: 20rpx;
			}

			.input {
				flex: 1;
				text-align: right;
			}

			.value-box {
				display: flex;
				align-items: center;
				justify-content: flex-end;
				flex: 1;
				margin-left: 10rpx;

				.value-info {
					font-size: 28rpx;
					color: #222222;
				}
			}

		}

		.form-item:last-child {
			border-bottom: 0;
		}
	}

	.select-box {
		background: #FFFFFF;
		padding: 34rpx 40rpx;
		border-radius: 16rpx;
		margin: 20rpx 32rpx;

		.select-title {
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-weight: bold;
			font-size: 26rpx;
			color: #2A0C00;

			.icon-select {
				width: 48rpx;
				height: 48rpx;
			}

			.input {
				flex: 1;
				text-align: right;
			}
		}

		.select-list {
			.select-item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				height: 100rpx;
				margin-top: 20rpx;

				.item-left {
					font-size: 28rpx;
					color: #666666;
				}

				.item-right {
					display: flex;
					align-items: center;

					.item-text {
						font-size: 28rpx;
						color: #222222;
						margin-right: 10rpx;
					}
				}
			}
		}
	}
</style>